extends Node2D

@onready var player: Ark_Player = $Player
@onready var mark: InvisibleMark = $InvisibleMark

const AUTO_MOVE_NONE = 0
const AUTO_MOVE = 1
const AUTO_MOVE_FIN = 2
const AUTO_MOVE_SPEED: float = 50
var auto_move_state = AUTO_MOVE_NONE

const SPAWN_POINT: Vector2 = Vector2(0, 53)

@onready var bubble1: TileMapLayer = $Bubble1
@onready var bubble2: TileMapLayer = $Bubble2
@onready var bubble3: TileMapLayer = $Bubble3
@onready var bubble4: TileMapLayer = $Bubble4

@onready var bubble_text1 = $Bubble1/Label
@onready var bubble_text2 = $Bubble2/Label
@onready var bubble_text3 = $Bubble3/Label
@onready var bubble_text4 = $Bubble4/Label

const BUBBLE_FADE_NONE: int = 0
const BUBBLE_FADE_IN: int = 1
const BUBBLE_FADE_IN_FIN: int = 2
var bubble_fade_state: int = 0
var current_bubble_index: int = 0
var elapsed: float = 0
var bubble_list: Array[TileMapLayer] = []
var bubble_text_list: Array[Label] = []

func start_show_bubble() -> void:
	bubble_fade_state = BUBBLE_FADE_IN

var alpha: float = 0

func bubble_fade_in(delta: float) -> void:
	if bubble_fade_state == BUBBLE_FADE_IN:
		elapsed += delta
		alpha = min(elapsed, 1)
		bubble_list[current_bubble_index].modulate.a = alpha
		bubble_text_list[current_bubble_index].modulate.a = alpha
		if bubble_list[current_bubble_index].modulate.a == 1:
			current_bubble_index += 1
			elapsed = 0
			if current_bubble_index == 4:
				bubble_fade_state = BUBBLE_FADE_IN_FIN
				player.controllable = true
		
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	bubble_fade_state = BUBBLE_FADE_NONE
	bubble_list.append(bubble1)
	bubble_list.append(bubble2)
	bubble_list.append(bubble3)
	bubble_list.append(bubble4)
	
	bubble_text_list.append(bubble_text1)
	bubble_text_list.append(bubble_text2)
	bubble_text_list.append(bubble_text3)
	bubble_text_list.append(bubble_text4)
	
	for bubble in bubble_list:
		bubble.modulate.a = 0
	for text in bubble_text_list:
		text.modulate.a = 0
	
	player.controllable = false
	auto_move_state = AUTO_MOVE
	player.velocity.x = AUTO_MOVE_SPEED
	player.position = SPAWN_POINT
	
	mark.player_stopped.connect(start_show_bubble)

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if auto_move_state == AUTO_MOVE and player.position.x > 35:
		player.velocity.x = 0
		player.controllable = true
		auto_move_state = AUTO_MOVE_FIN
	
	if bubble_fade_state == BUBBLE_FADE_IN:
		bubble_fade_in(delta)
	
	if player.position.y >= 257:  # 复位
		player.position = SPAWN_POINT
	
	if player.position.x >= 416:
		get_tree().change_scene_to_file("res://karte/karte_4.tscn")
